<template>
  <BaseMainSlot :show-search-box="false" :show-tab="true">
    <template v-slot:btn-box>
      <ActionBar
        :page-no="111"
        :has-edit="true"
        :add-active="addActive"
        :del-active="delActive"
        :cancel-active="cancelActive"
        :edit-active="editActive"
        :save-active="saveActive"
        @add="add"
        @cancel="cancel"
        @edit="edit"
        @del="del"
        @save="save"
      />
    </template>
    <template v-slot:tab-select>
      <SelectButton :buttonselectlist="buttonselectlist" @nowselectbuttonindex="batchstaumet" />
    </template>
    <!-- <template v-slot:farmtypeselectslot>
      <farm-type-select @chancefarmtype="chancefarmtype" />
    </template>-->
    <template v-slot:table-box>
      <!-- 展示和删除 -->
      <div style="height:100%;width:100%;">
        <div class="cardlist">
          <div
            v-for="(item,index) in tableData"
            :key="index"
            class="card"
            :class="{'cardselect':index===nowclickindex} "
            @click="clickcard(item,index)"
          >
            <el-checkbox
              v-if="item.isEditable"
              class="zhcheckbox"
              :value="nowselectedList[index]"
              @change="checkboxchange($event,index)"
              :disabled="!item.isEditable"
            />
            <!-- <div class="card-pest"></div> -->
            <div class="card-title">{{ item.title }}</div>
            <div class="card-date">更新时间：{{ item.timestamp }}</div>
            <div class="ql-editor" v-html="item.content"></div>
          </div>
        </div>
        <Pagination
          :page-size="pageSize"
          :current-page="currentPage"
          :total-size="totalSize"
          @changePageSize="changePageSize"
          @changeCurrentPage="changeCurrentPage"
        />
      </div>
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="dialogTitle + farmingTypeTitles + '知识信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
        width="50%"
      >
        <el-form ref="formData" label-position="left" :model="formData" class="el-form">
          <el-form-item label="知识标题:" class="w100p" prop="title"
            :rules="[
              { required: true, message: '知识标题不能为空', trigger: 'change'}
            ]">
            <el-input v-model="formData.title" clearable />
          </el-form-item>
          <el-form-item v-if="nowChanceStau == 'add'" label="种养类别:" class="w100p">
            <el-form-item
              class="w100p"
              style="width: calc(50% - 15px) !important; padding-left: 0 !important"
              prop="plantTypeNo"
            >
              <el-cascader
                v-model="selectplantlist"
                :options="planttypeList"
                :placeholder="nowplantTypeName"
                :disabled="nowChanceStau == 'edit'"
                :props="{checkStrictly: true, expandTrigger: 'hover',value: 'plantTypeNo',children:'children',label:'plantTypeName'}"
                @change="getpingzghong"
              />
            </el-form-item>
            <el-form-item
              class="w100p"
              style="width: calc(50% - 15px) !important; padding-left: 0 !important; margin-left: 30px;"
              prop="nowplantTypeName"
            >
              <el-select
                v-model="plantVarietyNo"
                :disabled="nowChanceStau == 'edit'"
                clearable
                placeholder="种养品种"
              >
                <el-option
                  v-for="(item,index) in nowvarietyList"
                  :key="index"
                  :label="item.plantVarietyName"
                  :value="item.plantVarietyNo"
                />
              </el-select>
            </el-form-item>
          </el-form-item>
          <el-form-item v-else label="种养品种:" class="w100p">
            <el-input v-model="plantVarietyName" disabled />
          </el-form-item>
          <el-form-item label="视频上传:" class="w100p">
            <el-form-item
              class="w100p"
              style="width: calc(50% - 15px) !important; padding-left: 0 !important"
              prop="videoUrl"
            >
              <el-upload
                class="upload-demo"
                :action="ImageUrl()"
                :on-change="handleResponse"
                :response-fn="handleResponse"
                :before-remove="handleRemove"
                :headers="headers"
                :file-list="fileList"
              >
                <el-button size="small" type="primary">点击上传视频</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item
              class="w100p"
              style="width: calc(50% - 15px) !important; padding-left: 0 !important; margin-left: 30px;"
              prop="videoUrl"
            >
              <el-input v-model="videoUrl" />
            </el-form-item>
          </el-form-item>
          <el-form-item label="知识正文:" class="w100p" prop="content"
            :rules="[
              { required: true, message: '知识正文不能为空', trigger: 'change'}
            ]">
            <quill-editor
              :style="{'height':richtextheight+'px', marginBottom: '60px'}"
              :content="formData.content"
              :options="editorOption"
              @change="onEditorChange($event)"
            />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import { mymixin } from "@/utils/mixin";
import nowpagereqs from "@/api/basic-info-manage/agricultural-type-manage";
import nowpagereq from "@/api/basic-info-manage/pest-knowledge-management";
import zhongyangleibie from "@/api/basic-info-manage/category-management/index";
import zhongyangpizhong from "@/api/basic-info-manage/breed-varieties-management/index";
import SelectButton from "@/components/selectbutton/index.vue";
// 引入富文本编辑器样式及组件
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
import { getToken } from "@/utils/auth";
import baseURL from "@/api/baseURL";
import { farmingTypeTitle } from "@/utils/validate";
export default {
  name: "PestKnowledgeManagement",
  components: {
    ActionBar,
    quillEditor,
    Pagination,
    BaseMainSlot,
    SelectButton
  },
  mixins: [mymixin],
  data() {
    return {
      formData: {

      },
      // 种养品种列表
      plantTypelList: [],
      nowplantTypeName: "",
      selectplantlist: [],
      farmingTypeTitles: farmingTypeTitle(),
      // 种养类别列表
      nowvarietyList: [],
      plantVarietyNo: "",
      // 背景图地址列表
      imageurllist: [
        { id: 1, url: "pest1.png" },
        { id: 2, url: "pest2.png" },
        { id: 3, url: "pest3.png" }
      ],
      // 当前选择状态管理
      nowselectedList: [],
      // 当前选中id管理
      nowselectedListtwo: [],
      // 当前点击的知识库index
      nowclickindex: "",
      // 当前点击的知识库id
      nowclickid: "",
      // 标题
      title: "",
      // 富文本内容
      richtextheight: 300,
      content: "",
      editorOption: {
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
            ["blockquote", "code-block"], // 引用  代码块
            [{ header: 1 }, { header: 2 }], // 1、2 级标题
            [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
            [{ script: "sub" }, { script: "super" }], // 上标/下标
            [{ indent: "-1" }, { indent: "+1" }], // 缩进
            [{ direction: "rtl" }], // 文本方向
            [
              {
                size: [
                  "12",
                  "14",
                  "16",
                  "18",
                  "20",
                  "22",
                  "24",
                  "28",
                  "32",
                  "36"
                ]
              }
            ], // 字体大小
            [{ header: [1, 2, 3, 4, 5, 6] }], // 标题
            [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
            // [{ font: ['songti'] }], // 字体种类
            [{ align: [] }], // 对齐方式
            ["clean"], // 清除文本格式
            ["image", "video"] // 链接、图片、视频
          ]
        },
        placeholder: "请输入正文"
      },
      dialogTitle: "",
      dialogFormVisible: false,
      planttypeList: [],
      buttonselectlist: [
        { name: "大田种植", value: "dt" },
        { name: "水产养殖", value: "sc" },
        { name: "大棚种植", value: "dp" },
        { name: "畜牧养殖", value: "xm" }
      ],
      curTabIndex: 0,
      plantVarietyName: null,

      videoUrl: null,
      fileList: []
    };
  },
  computed: {
    headers() {
      return {
        accessToken: sessionStorage.getItem("token"),
        organizationNo: sessionStorage.organizationNo,
        sysDataBaseName: sessionStorage.databaseName
      };
    }
  },
  watch: {
    nowChanceStau(newval) {
      // 当状态为删除的时候触发删除方法---另外的删除修改添加，通过点击保存，调用方法来实现
      if (newval === "add") {
        this.$set(this.formData, 'content', '')
        this.$set(this.formData, 'title', '')
        // this.editorOption = {
        //   placeholder: '编辑知识库文章'
        // }
      }
    }
  },
  created() {},
  mounted() {
    // this.getTableDataList()
  },
  methods: {
    // 视频地址
    ImageUrl() {
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        let URL = `${baseURL.webServiceUrl}v3/template/diseasesPestsInfo/uploadVideo`;
        return URL;
      } else {
        let URL = "#";
        // console.log(URL)
        return URL;
      }
    },
    async handleResponse(file, fileList) {
      let res = file?.response;
      if (res) {
        this.videoUrl =
          `${baseURL.webServiceUrl}v3/template/diseasesPestsInfo/video?` +
          res.data;
      }
      // return this.basicUrl + query/ + this.pictureNo
      // this.pictureNo = response.data;
      // customerManage.getImgByNo(this.pictureNo).then(res => {
      //   this.url = "data:image/png;base64," + res.data.pictureData;
      // })
      // return this.image;
    },
    handleRemove() {},

    batchstaumet(index) {
      this.curTabIndex = index;
      this.search();
      this.getselectdatalist();
      this.getpingzghong();
    },
    // 获取下拉框数据
    getselectdatalist() {
      nowpagereqs
        .getbaseFarmingTypeList({
          page: 1,
          size: 100,
          entity: { organizationNo: sessionStorage.organizationNo }
        })
        .then(res => {
          this.loadingtwo = false;
          if (res.code === 0) {
            this.$message.error("所有农业类型表格获取失败");
          }
          let data = res.data;
          // 赋值总条数
          this.totalSizetwo = data.totalElements;
          // 赋值数组
          this.buttonselectlist = [];
          data.content.forEach(item => {
            this.buttonselectlist.push({
              name: item.farmingTypeName,
              value: item.farmingTypeNo
            });
          });
        });
      // 获取种养类别列表
      // 获取种养类别树状表
      zhongyangleibie
        .getcategoryTreeTwo(this.buttonselectlist[this.curTabIndex].value)
        .then(res => {
          let list = res.data;
          this.planttypeList = this.filterTreeKey(list);
        });
    },
    // 循环过滤树形数组
    filterTreeKey(arr) {
      let newArr = [];
      newArr = arr?.map(item => {
        if (item.children?.length > 0) {
          item = {
            ...item,
            child: this.filterTreeKey(item.children)
          };
        } else {
          delete item.child;
        }
        return item;
      });
      newArr = newArr?.filter(item => item != null);
      return newArr;
    },
    // 获取虫情知识库内容
    getTableDataList() {
      let params = {
        size: this.pageSize,
        page: this.currentPage,
        entity: {
          farmingTypeNo: this.buttonselectlist[this.curTabIndex].value
        }
      };
      nowpagereq.getKnowledgeBaseList(params).then(res => {
        if (res.code === 0) {
          this.$message.error("查询失败");
        }
        let data = res.data;
        // 赋值总条数
        this.totalSize = data.totalElements;
        // 赋值数组
        this.tableData = data.content;
        // 赋值默认选择
        this.nowselectedList = [];
        this.tableData.forEach((item, index) => {
          // 管理状态
          this.nowselectedList.push(false);
          // 管理数据
          this.nowselectedListtwo.push("zh");
        });
        this.resetActionBar();
      });
    },
    // 多选框选择方法
    checkboxchange(e, index) {
      // this.nowselectedList[index] = e;
      this.$set(this.nowselectedList, index, e)
      if (e === true) {
        this.nowselectedListtwo[index] = this.tableData[
          index
        ].diseasesPestsInfoNo;
      } else {
        this.nowselectedListtwo[index] = "zh";
      }
      let bool = false
      this.nowselectedListtwo.forEach(item => {
        if (item !== "zh") {
          bool = true
        }
      });
      this.delActive = bool;
      this.cancelActive = bool;
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    // 图片地址返回方法
    imageurlmet(index) {
      let zilon = index % 3;
      let ukl = this.imageurllist[zilon]["url"];
      let ull = require(`@/assets/pest-knowledge/${ukl}`);
      // console.log(ull);
      // require 只接收一个动态值会报警告
      // return require(`@/assets/pest-knowledge/${ukl}`)
      return ull;
    },
    // 富文本高度自适应
    richheight(e) {
      if (e > 0) {
        this.richtextheight = e;
      } else {
        this.richtextheight = 100;
      }
    },
    // 富文本修改
    onEditorChange({ editor, html, text }) {
      this.$set(this.formData, 'content', html)
      this.$refs["formData"].validateField('content')
    },
    // 点击卡片方法
    clickcard(e, ide) {
      if (!e.isEditable) return
      this.nowclickindex = ide;
      this.nowclickid = e.diseasesPestsInfoNo;
      this.formData.title = e.title;
      this.editActive = true;
      this.plantVarietyNo = e.plantVarietyNo;
      // this.getpingzghongname(e.plantTypeNo)
      // console.log(e, '22222222222222');
      this.getvarriety(e.plantVarietyNo);
    },
    // 通过种养类别id查品种
    getpingzghong(e) {
      // alert("e")
      let plantTypeNo = this.selectplantlist[this.selectplantlist.length - 1];
      zhongyangpizhong
        .queryBycategoryPlantTypeNo(plantTypeNo || undefined)
        .then(res => {
          this.nowvarietyList = res.data;
        });
    },
    // 通过种养类别id查种养名称
    getpingzghongname(no) {
      let params = {
        plantTypeNo: no
      };
      zhongyangleibie.querybycondition(params).then(res => {
        this.nowplantTypeName = res.data[0].plantingTypeName;
      });
    },
    // 通过种养品种id查品种name
    getvarriety(plantVarietyNo) {
      let params = {
        plantVarietyNo: plantVarietyNo
      };
      zhongyangpizhong.queryBycategoryPlantTypeNo(params).then(res => {
        this.plantVarietyName = res.data[0].plantVarietyName;
      });
    },
    // 删除方法
    delmessage() {
      if (this.nowChanceStau === "del") {
        let zilonglist = this.nowselectedListtwo.map(item => {
          if (item !== "zh") {
            return item;
          }
        });
        nowpagereq.delKnowledgeBaselist(zilonglist).then(res => {
          if (res.code === 1) {
            this.getTableDataList();
            this.$message.success("删除成功");
          } else {
            this.$message.error("删除失败");
          }
        });
      }
    },
    // 添加
    add() {
      this.openDialog("add");
      this.plantTypeNo = null;
      this.plantVarietyNo = null;
      this.formData = {};
    },
    async edit() {
      let result = await nowpagereq.queryByNo(this.nowclickid);
      let data = result.data || {};
      this.formData.content = data.content;
      this.openDialog("edit");
    },
    // 取消
    cancel() {
      this.closeDialog();
      this.formData = {};
    },
    save() {
      this.$refs.formData.validate(valid => {
        if (valid) {
          let params = {
            // 种养品种id
            plantVarietyNo: this.plantVarietyNo,
            organizationNo: getToken("organizationNo"),
            account: sessionStorage.getItem("account"),
            farmingTypeNo: this.buttonselectlist[this.curTabIndex].value,
            content: this.formData.content,
            title: this.formData.title,
          };
          if (this.nowChanceStau === "add") {
            nowpagereq.addKnowledgeBaselist(params).then(res => {
              if (res.code === 1) {
                this.getTableDataList();
                this.closeDialog();
                this.$message.success("添加成功");
              } else {
                this.$message.error("添加失败");
              }
            });
          } else if (this.nowChanceStau === "edit") {
            params.diseasesPestsInfoNo = this.nowclickid;
            nowpagereq.editKnowledgeBaselist(params).then(res => {
              if (res.code === 1) {
                this.getTableDataList();
                this.closeDialog();
                this.$message.success("修改成功");
              } else {
                this.$message.error("修改失败");
              }
            });
          }
        }
      })
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.nowselectedList = [];
      this.dialogTitle = null;
      // this.canInput = false;
      // this.addActive = true;
      // this.delActive = false;
      // this.saveActive = false;
      // this.cancelActive = false;
      // this.editActive = false;
      this.resetActionBar();

      this.nowChanceStau = "";
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/styles/variables.scss";

.cardlist {
  display: flex;
  // width: 100%;
  // height: 100%;
  // flex-wrap:wrap;
  // overflow-y: auto;
  width: 100%;
  height: calc(100% - 60px);
  flex-wrap: wrap;
  overflow-y: auto;
  align-content: flex-start;
  justify-content: flex-start;
  border-radius: 5px 5px 5px 5px;
  opacity: 1;
  background: #0a404c;
  border: 1px solid #005e6a;
  .card {
    width: 100%;
    // margin-left: 2%;
    // margin-right: 2%;
    position: relative;
    height: 100px;
    padding: 10px;
    // background-color: cadetblue;
    background-position: center;
    // background-image: url("~@/assets/pest-knowledge/pest1.png");
    overflow: hidden;
    background-repeat: no-repeat;
    background-size: 85% 90%;
    padding-bottom: 20px;
    border-bottom: 1px dashed #0092a5;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    cursor: pointer;
    &:hover {
      border: 1px solid #0092a5;
      box-shadow: 0 0 10px 0 #0092a5;
    }
    // &:last-child{
    // border-bottom: 0px solid #0092A5;
    // }
    .ql-editor {
      overflow: hidden;
      height: 60%;
      padding: 5px 21px;
      text-overflow: ellipsis;
      cursor: pointer;
    }
    .card-pest {
      margin-top: 25%;
      width: 100%;
      font-weight: 500;
      text-align: center;
      white-space: nowrap;
    }
    .card-title {
      position: relative;
      top: 1%;
      width: 100%;
      font-weight: 500;
      text-align: start;
      font-size: 20px;
      font-weight: 400;
      white-space: nowrap;
      color: #57ffec;
    }
    .zhcheckbox {
      position: absolute;
      right: 10px;
      top: 10px;
    }
    .card-date {
      position: absolute;
      top: 10px;
      right: 70px;
      text-align: center;
      font-size: 10px;
      white-space: nowrap;
      color: #76beb6;
      // font-weight: 600;
    }
  }
  .cardselect {
    border: #00c29b 2px solid;
  }
}
.pagination {
  bottom: 20px;
  right: 20px;
}
::v-deep.el-checkbox {
  .el-checkbox__input .el-checkbox__inner {
    background-color: transparent;
  }
  .el-checkbox__inner::after {
    border: 1px solid #68c729;
    border-top: none;
    border-left: none;
  }
}
//----富文本-----
::v-deep.quill-editor {
  width: 100%;
  height: 100%;
  // 隐藏视频按钮
  // .ql-video{
  //   display: none;
  // }
  .ql-snow .ql-stroke {
    fill: none;
    // stroke: $appMainTextColor;
    stroke-linecap: round;
    stroke-linejoin: round;
    stroke-width: 2;
  }
  .ql-blank::before {
    color: #409eff;
  }
  // .ql-snow .ql-picker-options {
  //   background-color: $menuBg;}
  // .ql-snow .ql-picker {
  // color: $appMainTextColor;
  // }
  .ql-toolbar.ql-snow {
    border: 1px solid $themeColor;
  }
  .ql-container.ql-snow {
    border: 1px solid $themeColor;
    height: calc(100% - 40px);
  }
  .ql-selected {
    color: rgb(221, 117, 19);
  }
  // .ql-fill {
  // fill: $appMainTextColor;
  // }
}
</style>
